package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.common.BaseContext;
import com.itheima.domain.R;
import com.itheima.domain.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    //购物车添加功能
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart) {
        //A. 获取当前登录用户，为购物车对象赋值
        Long userId = BaseContext.getCurrentId();
        //B. 根据当前登录用户ID 及 本次添加的菜品ID/套餐ID，查询购物车数据是否存在
        shoppingCart.setUserId(userId);
        //C. 如果已经存在，就在原来数量基础上加1
        LambdaQueryWrapper<ShoppingCart> wapper = new LambdaQueryWrapper<>();
        if (shoppingCart.getDishId() != null) {
            wapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        }
        if (shoppingCart.getSetmealId() != null) {
            wapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        wapper.eq(ShoppingCart::getUserId, shoppingCart.getUserId());
        ShoppingCart cart = shoppingCartService.getOne(wapper);
        //D. 如果不存在，则添加到购物车，数量默认就是1
        if (cart != null) {
            cart.setNumber(cart.getNumber() + 1);
            //更新
            shoppingCartService.updateById(cart);
            return R.success("添加成功");
        }
        shoppingCart.setNumber(1);
        shoppingCartService.save(shoppingCart);
        return R.success(shoppingCart);
    }

    //查询登录用户购物车数据
    @GetMapping("/list")
    public R addList() {
        Long userID = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wapper = new LambdaQueryWrapper<>();
        wapper.eq(ShoppingCart::getUserId, userID);
        List<ShoppingCart> list = shoppingCartService.list(wapper);
        return R.success(list);
    }

    //清空购物车功能
    @DeleteMapping("/clean")
    public R clear() {
        Long currentId = BaseContext.getCurrentId();
        LambdaUpdateWrapper<ShoppingCart> wapper = new LambdaUpdateWrapper<>();
        wapper.eq(ShoppingCart::getUserId, currentId);
        shoppingCartService.remove(wapper);
        return R.success("清空成功");
    }

    //删除购物车中商品
    @PostMapping("/sub")
    public R remove(@RequestBody ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrentId();
        LambdaUpdateWrapper<ShoppingCart> wapper = new LambdaUpdateWrapper<>();
        shoppingCartService.getOne(wapper);
        return null;
    }
}